import {action, observable} from "mobx"
import {TableColumns} from './interfaces'
import request from '../../utils/request'
import apis from '../../config/apis'
import {Domain} from './interfaces'
import {CascaderOptionType} from "antd/lib/cascader";

class Store {
    @observable systems: Array<TableColumns> = []
    @observable app_name: string = ''
    @observable username: string = ''
    @observable page_num: number = 1
    @observable page_size: number = 50
    @observable total: number = 0
    @observable two: number | undefined = undefined
    @observable one: number | undefined = undefined
    @observable name: string = ''
    @observable beOffline: boolean = false
    initParams = () => {
        this.app_name = ''
        this.username = ''
        this.page_num = 1
        this.page_size = 50
        this.one = undefined
        this.two = undefined
        this.name = ''
        this.twoDomains = new Array<CascaderOptionType>()
        this.GetNamespaceList()
    }
    @action GetNamespaceList = async () => {
        const api = apis.GetNamespaceList
        const params = {
            name_cn: this.name || undefined,
            real_name: this.username || undefined,
            top_level_domain: this.one || undefined,
            second_level_domain: this.two || undefined,
            page_num: this.page_num,
            page_size: this.page_size,
            beOffline:this.beOffline
        }
        const data = await request(api, params)
        if (!data) {
            this.systems = []
            return
        }
        this.total = data.count
        this.systems = data.list
    }

    buildCascaderOptions = (arr: Domain[] | undefined): CascaderOptionType[] => {
        if (arr && arr.length) {
            return arr.map(v => {
                return {
                    label: v.domain_name,
                    value: v.id,
                    children: this.buildCascaderOptions(v.Child)
                } as CascaderOptionType
            })
        } else {
            return new Array<CascaderOptionType>()
        }
    }

    @observable twoDomains: CascaderOptionType[] | undefined = new Array<CascaderOptionType>()
    @observable domains: CascaderOptionType[] = new Array<CascaderOptionType>()
    @action GetDomain = async () => {
        const api = apis.GetDomain
        const resp = await request(api)
        if (!resp) return
        let data = resp as Domain[]
        let dm = this.buildCascaderOptions(data)
        this.domains = dm
    }
    delete_name_en = ''
    @action deleteNamespace = async () => {
        const api = apis.DeleteNs
        const resp = await request(api, {name_en: this.delete_name_en})
        if (!resp) return
        await this.GetNamespaceList()
    }
}

export default new Store()